# client_server.py
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/connect')
def connect():
    # 接收连接参数
    ip = request.args.get('ip', '').strip()
    port = request.args.get('port', '5000').strip()
    username = request.args.get('username', '').strip()
    password = request.args.get('password', '').strip()

    if not ip or not username or not password:
        return "❌ 缺少必要参数：IP、用户名或密码", 400

    # 校验 IP 格式（简单检查）
    try:
        parts = ip.split('.')
        if len(parts) != 4 or not all(0 <= int(p) <= 255 for p in parts):
            return "❌ 无效的 IP 地址", 400
    except:
        return "❌ 无效的 IP 地址", 400

    # 构造服务端 API 地址（用于前端连接）
    server_url = f"http://{ip}:{port}"
    api_path = f"/api/v1/Username={username}/Password={password}"

    return render_template(
        'remote.html',
        server_url=server_url,
        api_path=api_path,
        username=username,
        password=password
    )

if __name__ == '__main__':
    print("Run!")
    print("")
    app.run(host='0.0.0.0', port=8000)